package com.rsstuan.service;

import java.util.Collections;
import java.util.Properties;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

import com.google.appengine.api.memcache.jsr107cache.GCacheFactory;
import com.rsstuan.storage.impl.JDOImageStorage;

public class ImageService {
	
	private static JDOImageStorage imageStorage = new JDOImageStorage();
	
	private static ImageService instance = new ImageService();
	
	public static ImageService getInstance() {
		return instance;
	}
	private Logger LOG = Logger.getLogger(ChannelService.class.getName());

	private Cache cache;

	private Properties props = new Properties();
	
	public ImageService() {
		 try {
	            props.put(GCacheFactory.EXPIRATION_DELTA, 100);
	            CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
	            cache = cacheFactory.createCache(Collections.emptyMap());
	        }
	        catch (Exception e) {
	            
	        }
	}
	
	public void saveImage(Long itemId, byte[] data) {
		imageStorage.saveImage(itemId, data);
		putIntoCache(itemId, data);
	}

	public byte[] getImage(Long itemId) {
		byte[] data = loadFromCache(itemId);
		if (data == null) {
			data = imageStorage.getImage(itemId);
		}
		return data;
	}
	private void putIntoCache(Long itemId, byte[] data) {
		cache.put(itemId+"_img", data);
	}
	
	private byte[] loadFromCache(Long itemId) {
		byte[] data = (byte[])cache.get(itemId+"_img");
		if (data != null)
			return data.clone();
		return null;
	}

}
